package com.ledi.guns.modular.ledipay.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.ClassInfoMapper;
import com.ledi.guns.common.persistence.dao.StudentMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.ClassInfo;
import com.ledi.guns.common.persistence.model.Student;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.vo.StudentVo;
import com.ledi.guns.common.util.ExcelUtil;
import com.ledi.guns.config.properties.GunsProperties;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.support.BeanKit;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.clazz.StudentReq;
import com.ledi.guns.modular.ledipay.controller.req.clazz.Students;
import com.ledi.guns.modular.ledipay.controller.req.clazz.StudentsAdd;
import com.ledi.guns.modular.ledipay.controller.req.clazz.StudentsImport;
import com.ledi.guns.modular.ledipay.service.StudentService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.service.impl.StudentServiceImpl.java<br/>
 * 初始作者： 钟小平<br/>
 * 创建日期： 2018年8月2日<br/>
 * 功能说明： 这里用一句话描述这个类的作用--此句话需删除 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@Service
@Slf4j
public class StudentServiceImpl implements StudentService {

	protected final static Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);

	@Resource
	private StudentMapper studentMapper;

	@Resource
	private UserMapper userMapper;

	@Resource
	private ClassInfoMapper classInfoMapper;

	@Autowired
	private GunsProperties gunsProperties;

	/**
	 * 方法描述: [批量新增学生.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月2日-下午3:22:56<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public void addStudentsBatch(Students students) {

	}

	/**
	 * 方法描述: [新增学生.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月3日-上午11:37:12<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void addStudent(StudentsAdd studentsAdd) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}

		Student entity = new Student();
		BeanKit.copyProperties(studentsAdd, entity);
		entity.setSchoolId(schoolId);

		if (studentsAdd.getId() != null) {

			if (studentsAdd.getFlag() != null && studentsAdd.getFlag() == 1) {
				entity.setIsDelete(SystemConstans.YES);
			} else {
				setGradeId(studentsAdd.getClassId(), entity);
				Student stu = studentMapper.selectById(studentsAdd.getId());
				List<Student> selectList = studentMapper.selectList(new EntityWrapper<Student>()
						.eq("is_delete", 0)
						.eq("school_id", schoolId)
						.eq("name", studentsAdd.getName())
						.eq("parent_mobile", studentsAdd.getParentMobile()
								));
				if (CollectionUtils.isNotEmpty(selectList) && (!stu.getName().equals(studentsAdd.getName())
						|| !stu.getParentMobile().equals(studentsAdd.getParentMobile())
						)) {
					throw new AppCheckException("school.student.exit.code", "school.student.exit.message", studentsAdd.getName());
				}
			}
			entity.setUpdaterId(oneUser.getId());
			entity.setUpdateTime(new Date());
			entity.setUpdaterRole(oneUser.getRoleid());
			studentMapper.updateById(entity);
		} else {

			List<Student> selectList = studentMapper.selectList(new EntityWrapper<Student>()
					.eq("is_delete", 0)
					.eq("school_id", schoolId)
					.eq("name", studentsAdd.getName())
					.eq("parent_mobile", studentsAdd.getParentMobile())
					);
			if (CollectionUtils.isNotEmpty(selectList)) {
				throw new AppCheckException("school.student.exit.code", "school.student.exit.message", studentsAdd.getName());
			}
			entity.setCreatorId(oneUser.getId());
			entity.setCreateTime(new Date());
			entity.setIsDelete(SystemConstans.NO);
			entity.setCreatorRole(oneUser.getRoleid());
			oneUser.getRoleid();
			setGradeId(studentsAdd.getClassId(), entity);
			studentMapper.insert(entity);
		}

	}

	private void setGradeId(Long classId, Student entity) {

		ClassInfo classinfo = new ClassInfo();
		classinfo.setId(classId);
		classinfo.setIsDelete(SystemConstans.NO);
		ClassInfo selectOne = classInfoMapper.selectOne(classinfo);
		if (selectOne != null) {
			entity.setGradeId(selectOne.getGradeId());
		}
	}

	/**
	 * 方法描述: [学生列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月17日-下午3:52:18<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Page<StudentVo> studentList(Page<StudentVo> page, StudentReq req) {

		if (req.getSchoolId() != null && req.getClassId() != null) {

			List<StudentVo> list = studentMapper.pageList(page, req.getSearch());
			page.setRecords(list);
			return page;
		}
		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}
		req.setSchoolId(schoolId);

		if (!ShiroKit.isDirector()) {
			req.setMasterFlag(SystemConstans.NO);
			req.setUserId(Long.parseLong(oneUser.getId() + ""));
		}

		List<StudentVo> list = studentMapper.pageList(page, req.getSearch());
		page.setRecords(list);
		return page;
	}

	/**
	 * 方法描述: [班级批量导入学生.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月20日-上午10:11:35<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void importExcelStudents(MultipartFile file, Long classId) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}

		if (file == null) {
			throw new AppCheckException("students.import.null.code", "students.import.null.message");
		}

		ClassInfo selectById = classInfoMapper.selectById(classId);

		if (selectById == null || !selectById.getSchoolId().equals(schoolId)) {
			throw new AppCheckException("class.school.notFit.code", "class.school.notFit.message");
		}
		// 数据处理
		ExcelImportResult<StudentsImport> result = ExcelUtil.importExcelMore(file, 2, 1, StudentsImport.class);
		log.info("失败数据一共【" + result.getFailList().size() + "】行");
		List<StudentsImport> successList = result.getList();
		List<StudentsImport> failList = result.getFailList();
		log.info("是否存在验证未通过的数据:" + result.isVerfiyFail());
		log.info("验证通过的数量:" + successList.size());
		log.info("验证未通过的数量:" + failList.size());
		List<Student> list = new ArrayList<Student>();
		if (CollectionUtils.isEmpty(successList)) {
			throw new AppCheckException("class.students.success.null.code", "class.students.success.null.message");
		}
		Set<StudentsImport> setStudents = new LinkedHashSet<StudentsImport>(successList);
		for (StudentsImport student : setStudents) {
			log.info("成功列表信息:" + student.getParentMobile() + student.getName());
			student.setClassId(classId);
			Student s = new Student();
			BeanUtils.copyProperties(student, s);
			Map<String, Object> columnMap = new HashMap<String, Object>();
			columnMap.put("is_delete", SystemConstans.NO);
			columnMap.put("school_id", schoolId);
			columnMap.put("parent_mobile", student.getParentMobile());
			columnMap.put("name", student.getName());
			columnMap.put("class_id", classId);
			List<Student> selectByMap = studentMapper.selectByMap(columnMap);
			if (CollectionUtils.isNotEmpty(selectByMap)) {
				throw new AppCheckException("class.students.repeat.code", "class.students.repeat.message", student.getName());
			}
			s.setCreatorId(oneUser.getId());
			s.setCreateTime(new Date());
			s.setIsDelete(SystemConstans.NO);
			s.setCreatorRole(oneUser.getRoleid());
			s.setSchoolId(schoolId);
			s.setGradeId(selectById.getGradeId());
			list.add(s);
		}
		for (StudentsImport user : failList) {
			log.info("失败列表信息:" + user.getName());
		}
		studentMapper.insertBatch(list);
		if (result.isVerfiyFail()) {
			throw new AppCheckException("class.students.verify.code", "class.students.verify.message", failList.get(0).getName());
		}
	}
}
